package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryWithTree() {
        // 查询所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 1. 获取一级分类
        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((meun) -> {
            // 2. 为每一个一级分类添加子分类
            meun.setChildren(getChildren(meun.getCatId(), categoryEntities));
            return meun;
            // 3. 排序
        }).sorted((menu1, menu2) ->
                (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());

        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name") //代表当前方法的结构需要缓存，如果缓存中有，方法不调用，如果缓存中没有则调用并将结果放入缓存
    //**默认使用jdk进行序列化（可读性差），默认ttl为-1永不过期，自定义序列化方式需要编写配置类**
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        /**
         * 1. 空结果缓存：解决缓存穿透问题
         * 2. 设置过期实践（加随机值）：解决缓存雪崩问题
         * 3. 加锁：解决缓存击穿问题
         */
        // 加缓存
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");

        if (StringUtils.isEmpty(catalogJSON)) {

            Map<String, List<Catelog2Vo>> catelogJsonFromDB = getCatelogJsonFromDBWithRedissionLock();
            String s = JSON.toJSONString(catelogJsonFromDB);
            stringRedisTemplate.opsForValue().set("catalogJSON", s);
        }

        Map<String, List<Catelog2Vo>> map = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return map;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDBWithRedissionLock() {
        RLock lock = redissonClient.getLock("CatalogJson-lok");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getCatelogJsonFromDB();
        }finally {
            lock.lock();
        }

        return dataFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDB() {
        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        // 优化：将查询变为一次
        List<CategoryEntity> entityList = baseMapper.selectList(null);

        // 查询所有一级分类
        List<CategoryEntity> level1 = getCategoryEntities(entityList, 0L);


        return level1Categorys.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), value -> {
            // 通过一级分类找到其对应的所有二级分类
            List<CategoryEntity> categoryEntities = getCategoryEntities(entityList, value.getCatId());
//                    baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", value.getCatId()));
            // 封装上面的结果,将二级分类对象封装成二级VO并将三级VO放入二级VO中
            List<Catelog2Vo> catelog2VoList = null;
            if (categoryEntities != null) {
                catelog2VoList = categoryEntities.stream().map(item -> {
                    //将二级分类对象封装成二级VO
                    Catelog2Vo catelog2Vo = new Catelog2Vo(value.getCatId().toString(), item.getName(), item.getCatId().toString(), null);
                    // 先查出二级分类的所有三级分类
                    List<CategoryEntity> categoryEntity3 = getCategoryEntities(entityList, item.getCatId());
//                            baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item.getCatId()));
                    // 将三级分类转化成三级VO
                    if (categoryEntity3 != null) {
                        List<Catelog2Vo.Catalog3Vo> collect = categoryEntity3.stream().map(i3 -> {
                            Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(i3.getCatId().toString(), i3.getName(), item.getCatId().toString());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        // 将三级分类VO塞进去
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
    }

    /**
     * 第一次查询的所有 CategoryEntity 然后根据 parent_cid去这里找
     */
    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> entityList, Long parent_cid) {

        return entityList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }


    private List<CategoryEntity> getChildren(Long id, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == id
        ).map((menu) -> {
            // 递归调用
            menu.setChildren(getChildren(menu.getCatId(), categoryEntities));
            return menu;
        }).sorted((menu1, menu2) ->
                (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());
        return collect;
    }



}